require("./src/model/sync");
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const fileUrl = require("./src/tools/fileUrl");
const verifyTokenMiddleware = require("./src/routes/verifyTokenMiddleware");
const path = require("path");
const https = require("https");
const fs = require("fs");

const app = express();

app.use(bodyParser.urlencoded({ limit: "5000mb" }));
//解析JSON格式的请求体数据
app.use(bodyParser.json({ limit: "5000mb", extended: true }));
app.use(cors());

const UserRoute = require("./src/routes/api/user");
const NewsRoute = require("./src/routes/api/news");
const uploadRoute = require("./src/routes/api/uploadRoute");

//设置允许跨域访问该服务.
app.all("*", function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Content-Type");
  res.header("Access-Control-Allow-Methods", "*");
  next();
});

//用户中间件
app.use("/api/user", UserRoute);
//上传中间件
app.use("/api/upload", uploadRoute);
app.use("/api/news", NewsRoute);
//错误处理中间件
app.use(require("./src/routes/errorMiddleware"));

app.use(express.static(__dirname + "/public", { index: "index.html" }));
app.use("/public/uploads", express.static(fileUrl.videoStaticPath));
app.use("*", (req, res) => {
  res.sendFile(path.resolve(__dirname, "public", "index.html"));
});

const privateCrt = fs.readFileSync(
  path.join(process.cwd(), "cert/www.cobotsys.com_bundle.crt"),
  "utf8"
);
const privateKey = fs.readFileSync(
  path.join(process.cwd(), "cert/www.cobotsys.com.key"),
  "utf8"
);
const credentials = {
  key: privateKey,
  cert: privateCrt,
};

const HTTPS_PORT = 443;
const httpsServer = https.createServer(credentials, app);
httpsServer.listen(HTTPS_PORT, () => {
  console.log(`HTTPS Server running on port ${HTTPS_PORT}`);
});
